from os import path

from flask import Blueprint, request, send_file
from werkzeug.datastructures import FileStorage

from apps.logger_config import logger
from apps.model import HouseApprove, HouseConfirm
from apps.model.file import File
from apps.utils import Response as ResponseUtil
from apps.utils.static_file import basepath

file = Blueprint('file', __name__)

approve_base_path = path.abspath(path.join(path.dirname(path.abspath(__file__)), '../../static/chanquan'))


@file.route('/upload', methods=['POST'])
def upload():
    f: FileStorage = request.files['file']
    uuid = File.save_file_bytes(f)
    logger.info('%s 文件上传至文件夹 %s', f.filename, uuid)
    return ResponseUtil.success({'id': uuid})


@file.route('/download', methods=['GET'])
def download():
    uuid = dict(request.args).get('id')
    file_path = path.join(basepath, uuid)
    if not path.exists(file_path):
        raise Exception("文件不存在")
    file_record = File.get(uuid)
    if file_record is None:
        raise Exception("文件不存在")
    return send_file(file_path, as_attachment=True, attachment_filename=file_record.file_name)


@file.route('/downloadApprove', methods=['GET'])
def downloadApprove():
    uuid = dict(request.args).get('id')
    data = HouseApprove.filter_by(file=uuid).first()
    if data is None:
        data = HouseConfirm.filter_by(file=uuid).first()
    if data is None:
        raise Exception("文件不存在")
    file_path = path.join(approve_base_path, uuid)
    if not path.exists(file_path):
        raise Exception("文件不存在")
    return send_file(file_path, as_attachment=True, attachment_filename=data.qz_no + '.pdf')
